#include "BatteryChargingStateModel.h"
#include "Common/DataStructureMacro.h"
#include "ssas_api.h"
#define LOG_TAG "HMI"
#include "log_api.h"

#define BATTERY_OK 1
#define BATTERY_NOT_OK 0

typedef enum 
{
    ALWAYS_OFF,
    ALWAYS_ON,
} MachineState;

static MachineState currentStatus;
static Option_U8    showFlag;
static uint8_t      widget_visible_mask = 0;

static void init()
{
    currentStatus = ALWAYS_OFF;
    showFlag.value_ = 0;
    showFlag.update_ = false;
}

static MachineState getNewState()
{
    MachineState newStatus = ALWAYS_ON;
    int msgState = COM_MSG_INIT;
    Std_ReturnType comRet = E_NOT_OK;

    do
    {
        if(!isFinishSelfTest(SELF_TEST_3S))
        {
            newStatus = ALWAYS_ON;
            break;
        }

        msgState = get_message_state(COM_IC_HCU_GENERAL_STATUS_1);
        if(COM_MSG_TIMEOUT == msgState || COM_MSG_INIT == msgState/*todo maybe remove*/)
        {
            msgState = ALWAYS_ON;
            break;
        }

        int rawData = 0;
        comRet = Com_ReceiveSignal(COM_SID_VCUVehModCntSts, &rawData);
        if(E_NOT_OK == comRet)
        {
            newStatus = ALWAYS_ON;
            break;
        }

        if(BATTERY_NOT_OK == rawData)
        {
            newStatus = ALWAYS_ON;
        }
        else
        {
            newStatus = ALWAYS_OFF;
        }


    } while (false);
    
    return newStatus;
}

static void handlStateTransition(MachineState newStatus)
{
    if(currentStatus != newStatus)
    {  
        currentStatus = newStatus;
    }
}

static void postprocess()
{
    switch (currentStatus)
    {
        case ALWAYS_OFF:
            setOptionValue_U8(&showFlag, false);
            break;

        case ALWAYS_ON:
            setOptionValue_U8(&showFlag, true);
            break;
        
        default:
            LOG_E("Hibeam unknow status : %d\n", currentStatus);
            break;
    }
}

static void run()
{
    MachineState newStatus = getNewState();
    handlStateTransition(newStatus);
    postprocess(); 
}

static void release()
{

}

BatteryChargingStateModel g_BatteryChargingStateModelInstance = {
    {
        init,
        run,
        release,
        MIN_PERIOD,
    },
};

// ----------------------------------View------------------------------
void refresh_tt14View(ItuElement* elememt, bool isUnconditional)
{
    if(showFlag.update_)
    {
        ituCheckBoxSetChecked((ITUCheckBox*)elememt->widget_, showFlag.value_);
        showFlag.update_ = false;
    }
}

void reporting_self_validity_tt14View(ItuElement* elememt)
{
    uint8_t is_visible = (elememt && elememt->isVaild_) ? 0x01 : 0x00;
    widget_visible_mask <<= 1;
    widget_visible_mask |= is_visible;
}